import random

from django.http import HttpResponseForbidden, HttpResponse
from django_redis import get_redis_connection
from rest_framework.views import APIView,Response

from libs.captcha.captcha import captcha
# Create your views here.
from django.views import View


# from verificationsapp.tasks import send_sms

class ImageCodeView(View):
    def get(self, request):
        # 1.接收数据uuid
        uuid = request.GET.get('uuid')
        # 2.校验数据
        if not uuid:
            return HttpResponseForbidden('uuid无效')
        # 3.处理业务
        # 获取图片文本内容和图片二进制代码
        text, image = captcha.generate_captcha()  # text=GPMZ image=图片
        # 4.把uuid和图片文本存入redis
        redis_client = get_redis_connection('img_code')  # 获取redis客户端
        # 5.写入redis(是字符串)
        redis_client.setex(uuid, 60 * 5, text)
        # 6.返回响应图片
        return HttpResponse(image, content_type='image/jpg')

class SendSMCode(APIView):
    # 发送获取短信验证码
    def post(self, request):
        phone = request.data.get('phone')
        image_code = request.data.get('image_code')
        image_code_uuid = request.data.get('image_code_uuid')
        print(phone,image_code,image_code_uuid)
        if not all([phone, image_code, image_code_uuid]):
            return Response({'code': 4005, 'msg': '参数不全'})

        redis_client = get_redis_connection('img_code')
        redis_img_code = redis_client.get(image_code_uuid).decode()
        if image_code.lower() != redis_img_code.lower():
            return Response({'code':4003,'msg':'参数错误'})

        #发送短信
        num = random.randint(100000,999999)
        send_data = {'code':num}
        print(send_data)
        # send_sms.delay(phone,send_data)
        print(send_data)
        #删除redis里的image_code 保存phone_code
        # redis_client.setex(phone,60*60,num)
        # redis_client.delete(image_code_uuid)
        # # #pipeline管道：作用就是把多个命令放在一起来执行
        pl = redis_client.pipeline()
        pl.setex(phone, 60 * 5, num)
        pl.delete(image_code_uuid)
        pl.execute()
        return Response({'code':0,'msg':'发送成功'})